package cmich.cps.scheduler;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.logging.Logger;

import cmich.cps.scheduler.data.Course;
import cmich.cps.scheduler.gui.Prompts;

import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.EbeanServerFactory;
import com.avaje.ebean.config.DataSourceConfig;
import com.avaje.ebean.config.ServerConfig;

/**
 * The Class DatabaseServer.
 * 
 * @author Jonathan Kissinger <kissi1j@cmich.edu>
 */
public class DatabaseServer {

	/** The Constant LOGGER. */
	private final static Logger LOGGER = Logger.getLogger(Course.class.getName());

	/**
	 * Sets up the database server.
	 *
	 * @param reset true to reset the database
	 */
	public static void setup(Boolean reset, File dir) {
		String name = "scheduler";
		String dbPath = dir + File.separator + "data" + File.separator + name;
		File db = new File(dbPath + ".h2.db");
		ServerConfig config = new ServerConfig();
		config.setName(name);
		config.setDefaultServer(true);

		if((reset && Prompts.getInstance().confirm("Are you sure you want to reset the database?")) || !db.exists()) {
			LOGGER.info("Resetting database.");
			config.setDdlGenerate(true);  
			config.setDdlRun(true);
		}

		DataSourceConfig h2Db = new DataSourceConfig();  
		h2Db.setDriver("org.h2.Driver");  
		h2Db.setUsername("cmich");  
		h2Db.setPassword("password");
		
		File jar = getJarFile();
		if(jar!=null) {
			config.addJar(jar.getName());  
		}

		LOGGER.config("Storing database at: " + dbPath);
		h2Db.setUrl("jdbc:h2:file:" + dbPath);  
		h2Db.setHeartbeatSql("select 1");
		config.setDataSourceConfig(h2Db);
		config.setDefaultServer(true);
		EbeanServer server = EbeanServerFactory.create(config);
		LOGGER.config("Database Server started: " + server.getName());
	}

	public static File getJarFile() {
		String path = DatabaseServer.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		try {
			String decodedPath = URLDecoder.decode(path, "UTF-8");
			File myJar = new File(decodedPath);
			LOGGER.finest("This jar file: " + myJar);
			if(myJar.getName().endsWith(".jar")) return myJar;
		} catch (UnsupportedEncodingException e) {
			LOGGER.warning(e.toString());
		}
		return null;
	}

}
